import jwt from 'jsonwebtoken'
import { config } from "../config";
/***
 * 
 */
const findMembers = function (instance: any, {
    prefix,
    specifiedType,
    filter
}: any) {
    // 递归函数
    function _find(instance: any): any {
        //基线条件（跳出递归）
        if (instance.__proto__ === null)
            return []

        let names = Reflect.ownKeys(instance)
        names = names.filter((name) => {
            // 过滤掉不满足条件的属性或方法名
            return _shouldKeep(name)
        })

        return [...names, ..._find(instance.__proto__)]
    }

    function _shouldKeep(value: any) {
        if (filter) {
            if (filter(value)) {
                return true
            }
        }
        if (prefix)
            if (value.startsWith(prefix))
                return true
        if (specifiedType)
            if (instance[value] instanceof specifiedType)
                return true
    }

    return _find(instance)
}

const generateToken = function (name: any) {
    const secretKey = config.SEC.secretKey
    const expiresIn = config.SEC.expiresIn
    const token = jwt.sign({
        name
    }, secretKey, {
        expiresIn
    })
    return token
}

const lostTime = (createdAt: Date) => {
    const date = new Date(createdAt).getTime()
    const now = Date.now()
    const timeDifference = now - date
    let str = ''
    if (timeDifference < 60000) {
        str = '刚刚'
    } else if (timeDifference < 3600000) {
        str = Math.floor(timeDifference / 60000) + '分钟前'
    } else if (timeDifference < 86400000) {
        str = Math.floor(timeDifference / 3600000) + '小时前'
    } else if (timeDifference < 2592000000) {
        str = Math.floor(timeDifference / 86400000) + '天前'
    } else if (timeDifference < 31104000000) {
        str = Math.floor(timeDifference / 2592000000) + '月前'
    } else {
        str = Math.floor(timeDifference / 31104000000) + '年前'
    }
    return str
}

export {
    findMembers,
    generateToken, lostTime
}



// const generateToken = function (uid, scope) {
//     const secretKey = global.config.security.secretKey
//     const expiresIn = global.config.security.expiresIn
//     const token = jwt.sign({
//         uid,
//         scope
//     }, secretKey, {
//         expiresIn: expiresIn
//     })
//     return token
// }